package com.zj.osm.view.home.home.home_fragment.twofragment.page;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;

import com.flyco.dialog.widget.NormalDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.adapter.ProjectAdapter;
import com.zj.osm.bean.Filter;
import com.zj.osm.bean.LocalSelectedEnum;
import com.zj.osm.entity.db.EquipmentDao;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.PhotosDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.db.ProjectDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Photos;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.mvp.MvpFragment;
import com.zj.osm.utils.ExportUnit;
import com.zj.osm.utils.ZipUtil;
import com.zj.osm.view.home.home.home_fragment.onefragment.OneFragment;
import com.zj.osm.view.home.home.home_fragment.onefragment.ProjectAdapterInterface;
import com.zj.osm.view.map.map.MapActivity;
import com.zj.utils.data.LiveDataBus;
import com.zj.utils.utils.ShareUtils;
import com.zj.utils.utils.ThreadManager;
import com.zj.utils.utils.TimeUtils;
import com.zj.utils.utils.http.HttpConfig;
import com.zj.utils.utils.utilcode.ToastUtils;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;
import static com.blankj.utilcode.util.FileUtils.deleteDir;
import static com.zj.osm.utils.Configuration.PROJECT_ID;
import static com.zj.osm.view.home.home.home_fragment.onefragment.OneFragment.parseXMLWithPulls;
import static com.zj.utils.utils.ThreadManager.getThreadPool;

/**
 * <pre>
 *     author : luhenchang
 *     e-mail : 1276998208@qq.com
 *     time   : 2019/12/05
 *     desc   : 版权所有
 *     version: 1.0
 * </pre>
 */
public class LocalProjectFragment extends LinearLayout implements ProjectAdapterInterface {

    private ListView two_listView;
    private LinearLayout two_linear;
    private CheckBox two_cb_check;
    private Button two_btn_delete;
    private Button two_btn_daochu;
    private Button two_btn_shangchuan;
    private SmartRefreshLayout local_refreshLayout;
    private ProjectAdapter adapter;
    private List<Project> list;
    private Context mcontext;
    private TextView two_tv_name;
    private ThreadManager.ThreadPool threadPool;
    private OnButtonVisibleListenner onButtonVisibleListenner;

    public LocalProjectFragment(Context context) {
        this(context, null);
    }

    public LocalProjectFragment(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LocalProjectFragment(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mcontext = context;
        View view = View.inflate(context, R.layout.fragment_local, this);
        initView(view);

    }

    public LocalProjectFragment(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    private void initView(View view) {
        threadPool = getThreadPool();
        two_listView = view.findViewById(R.id.two_listView);
        two_tv_name = view.findViewById(R.id.two_tv_name);
        two_linear = view.findViewById(R.id.local_linear);
        two_cb_check = view.findViewById(R.id.two_cb_check);
        two_btn_delete = view.findViewById(R.id.two_btn_delete);
        two_btn_daochu = view.findViewById(R.id.two_btn_daochu);
        two_btn_shangchuan = view.findViewById(R.id.two_btn_shangchuan);
        local_refreshLayout = view.findViewById(R.id.local_refreshLayout);
        initListenner();
    }

    /**
     * 当Fragment获取焦点时候获取数据
     **/
    public void getOnResum() {
        list.clear();
        List<Project> dataList = App.getInstances().getDaoSession().getProjectDao().queryBuilder().orderDesc(ProjectDao.Properties.Id).build().list();
        list.addAll(dataList);
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    private void initListenner() {
        local_refreshLayout.setEnableLoadMore(false);
        local_refreshLayout.setOnRefreshListener(refreshment -> {
            long start = System.currentTimeMillis();
            list = App.getInstances().getDaoSession().getProjectDao().queryBuilder().orderDesc(ProjectDao.Properties.Id).build().list();
            if (adapter != null)
                adapter.notifyDataSetChanged();
            long stop = System.currentTimeMillis() - start;
            refreshment.finishRefresh((int) stop);
        });


        two_listView.setOnItemClickListener((parent, views, position, id) -> {
            Project items = (Project) adapter.getItem(position);
            if (items.getState().equals("在线")) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("surverytaskid", items.getProjectId());
                String result = HttpConfig.callService(0, "getProjectStatusInfo", map);
                if (parseXMLWithPulls(result)) {
                    ToastUtils.showShort("此项目已结束勘测");
                } else {
                    LiveDataBus.get().getChannel(PROJECT_ID).setValue(items.getId());
                    Intent intent = new Intent(getContext(), MapActivity.class);
                    intent.putExtra("name", items.getState());
                    intent.putExtra("id", items.getId());
                    startActivity(intent);
                }
            } else {
                Log.e("projectIdOne==", items.getId().toString());
                LiveDataBus.get().getChannel(PROJECT_ID).setValue(items.getId());
                Intent intent = new Intent(getContext(), MapActivity.class);
                intent.putExtra("name", items.getState());
                intent.putExtra("id", items.getId());
                startActivity(intent);
            }

        });


    }

    /**
     * 初始化数据
     */
    public void init(MvpFragment mvpFragment) {
        onButtonVisibleListenner = (OnButtonVisibleListenner) mvpFragment;
        list = App.getInstances().getDaoSession().getProjectDao().queryBuilder().orderDesc(ProjectDao.Properties.Id).build().list();
        if (list.size() > 0) {
            adapter = new ProjectAdapter(mcontext, list, this);
            two_listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            two_tv_name.setVisibility(View.GONE);
        } else {
            two_tv_name.setVisibility(View.VISIBLE);
        }

    }


    @Override
    public void getProjectList() {
        list.clear();
        List<Project> dataList = App.getInstances().getDaoSession().getProjectDao().queryBuilder().orderDesc(ProjectDao.Properties.Id).build().list();
        list.addAll(dataList);
        if (list.size() > 0) {
            two_tv_name.setVisibility(View.GONE);
        } else {
            two_tv_name.setVisibility(View.VISIBLE);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void setAsc() {
        list.clear();
        List<Project> dataList = App.getInstances().getDaoSession().getProjectDao().queryBuilder().orderAsc(ProjectDao.Properties.Id).build().list();
        list.addAll(dataList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void setDesc() {
        list.clear();
        List<Project> dataList = App.getInstances().getDaoSession().getProjectDao().queryBuilder().orderDesc(ProjectDao.Properties.Id).build().list();
        list.addAll(dataList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void setOtherOrder(LocalSelectedEnum selectWhere, Filter filter) {
        switch (selectWhere) {
            case LOCAL_TYPE:
                for (int j = 0; j < list.size(); j++) {
                    if (!list.get(j).getState().equals(filter.getValue())) {
                        list.remove(list.get(j));
                    }
                }
                adapter.notifyDataSetChanged();
                break;
            case PROJECT_STATE:
                for (int j = 0; j < list.size(); j++) {
                    if (!list.get(j).getType().equals(filter.getValue())) {
                        list.remove(list.get(j));
                    }
                }
                adapter.notifyDataSetChanged();
                break;
            case VOLTAGE_LEVEL:
                for (int j = 0; j < list.size(); j++) {
                    if (!list.get(j).getVoltage().equals(filter.getValue())) {
                        list.remove(list.get(j));
                    }
                }
                adapter.notifyDataSetChanged();
                break;

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void setGuanliListItem(int visible, boolean ischeck) {
        if (!ischeck) {
            two_linear.setVisibility(visible);
            initDialog();
            two_cb_check.setChecked(false);
        } else {
            two_linear.setVisibility(View.GONE);
            for (int i = 0; i < list.size(); i++) {
                //这如果使用第一种方法会修改不了数据，也不尝试全使用这个了，等有时间了试试。
                Project items = list.get(i);
                items.setBatchCheck(0);
                App.getInstances().getDaoSession().getProjectDao().update(items);
            }
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initDialog() {
        two_cb_check.setOnCheckedChangeListener((buttonView, isChecked) -> {//全选
            if (isChecked) {
                setBatch(1);
            } else {
                setBatch(0);
            }
            adapter.notifyDataSetChanged();
        });
        two_btn_delete.setOnClickListener(v -> { //批量删除
            startDialog();
        });
        two_btn_daochu.setOnClickListener(v -> {//批量导出
            List<Project> itemsList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getBatchCheck() == 1) {
                    itemsList.add(list.get(i));
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort("没有选中项目");
                }
            }
            ExportUnit exportUnit = new ExportUnit(getContext(), itemsList.get(0).getId(), itemsList.get(0).getName());
            if (itemsList.size() == 1) {
                exportUnit.SetLocalExport();
            } else {

                List<File> fileList = new ArrayList<>();
                List<File> filePath = new ArrayList<>();
                for (int j = 0; j < itemsList.size(); j++) {
                    filePath.add(exportUnit.getXmlFile());
                    fileList.add(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + itemsList.get(j).getName()));
                }
                if (itemsList.size() > 0)
                    startZip(filePath, fileList, itemsList.get(0).getName() + "...");
                else
                    com.blankj.utilcode.util.ToastUtils.showShort("请选择项目");
            }
        });
        two_btn_shangchuan.setOnClickListener(v -> {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getBatchCheck() == 1) {
                    com.blankj.utilcode.util.ToastUtils.showShort("上传成功");
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort("没有选中项目");
                }
            }
        });
    }

    /**
     * 设置是否全选
     *
     * @param flag 1为全选 0为不选
     */
    private void setBatch(int flag) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setBatchCheck(flag);
            App.getInstances().getDaoSession().getProjectDao().update(list.get(i));
        }
    }

    /**
     * 批量删除设备对话框
     */
    public void startDialog() {

        final NormalDialog dialog = new NormalDialog(getContext());
        dialog.content("您确定要删除吗?")//
                .style(NormalDialog.STYLE_TWO)//
                .btnNum(2)
                .title("批量删除设置")
                .btnText("取消", "删除")//
                .show();
        dialog.setOnBtnClickL(
                dialog::dismiss, () -> {
                    dialog.dismiss();
                    createProgressDialog();
                    threadPool.execute(() -> {
                        delete();
                        Message msg = deletehandler.obtainMessage();
                        msg.what = 1;
                        deletehandler.sendMessage(msg);
                    });

                });
    }

    @SuppressLint("HandlerLeak")
    private Handler deletehandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //若工作完成，取消动画，初始化界面
                if (mProgressDialog != null) {
                    mProgressDialog.cancel();
                }
                com.blankj.utilcode.util.ToastUtils.showShort("删除成功");
                OneFragment.DIALOG_BOTTOM = true;
                two_linear.setVisibility(View.GONE);
                //通知TwoFragment进行跟新关闭文字。
                onButtonVisibleListenner.onButtonVisibleListener();
                setAsc();
            }
        }
    };
    private ProgressDialog mProgressDialog;

    /**
     * 创建ProrgressDialog
     */
    private void createProgressDialog() {
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setMessage("删除数据中,请稍等...");
        mProgressDialog.show();
    }

    /**
     * 实现批量删除
     */
    private void delete() {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getBatchCheck() == 1) {
                //删除所有相关联的数据
                App.getInstances().getDaoSession().getProjectDao().deleteByKey(list.get(i).getId());
                List<Point> pointsList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(list.get(i).getId())).build().list();
                for (int j = 0; j < pointsList.size(); j++) {
                    App.getInstances().getDaoSession().getPointDao().delete(pointsList.get(j));
                    List<Equipment> equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(pointsList.get(j).getId())).build().list();
                    if (equipmentList.size() > 0)
                        for (int f = 0; f < equipmentList.size(); f++) {
                            App.getInstances().getDaoSession().getEquipmentDao().delete(equipmentList.get(f));
                        }
                    List<Photos> photosList = App.getInstances().getDaoSession().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(pointsList.get(j).getId())).build().list();
                    if (photosList.size() > 0)
                        for (int z = 0; z < photosList.size(); z++) {
                            App.getInstances().getDaoSession().getPhotosDao().delete(photosList.get(z));
                        }
                }
                List<Line> lines = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(list.get(i).getId())).build().list();
                for (int z = 0; z < lines.size(); z++) {
                    App.getInstances().getDaoSession().getLineDao().delete(lines.get(z));
                }
                try {
                    deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/bhne/" + list.get(i).getName());
                    deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/bhne/" + list.get(i).getName() + ".zip");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }


    /**
     * 批量导出信息对话框以及实现
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void startZip(final List<File> paths, final List<File> filePaths, final String name) {
        @SuppressLint("InflateParams") View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_add_concealed_dialog, null);
        Button alertSureTv = view.findViewById(R.id.add_sure);
        Button alertCancelTv = view.findViewById(R.id.add_cancle);
        CheckBox alertCheckBox = view.findViewById(R.id.add_cb);
        alertCheckBox.setChecked(true);
        //显示确认框
        AlertDialog mAlertDialog = new AlertDialog.Builder(Objects.requireNonNull(getContext())).setView(view).create();
        mAlertDialog.show();
        //取消
        alertSureTv.setOnClickListener(view1 -> mAlertDialog.cancel());
        //导出
        alertCancelTv.setOnClickListener(view12 -> {
            if (alertCheckBox.isChecked()) {
                List<File> zipFiles = new ArrayList<>();
                for (int i = 0; i < filePaths.size(); i++) {
                    Log.e("fileImformation=", filePaths.get(i).getName());
                    ZipUtil.zip(filePaths.get(i).getAbsolutePath(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + filePaths.get(i).getName() + ".zip");
                    zipFiles.add(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + filePaths.get(i).getName() + ".zip"));
                }
                ZipUtil.zipFiles(zipFiles, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + "Mul" + ".zip");
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + "Mul" + ".zip");
                ShareUtils.shareFile(getContext(), file);
            } else {
                ZipUtil.zipFiles(paths, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + "No" + ".zip");
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + "No" + ".zip");
                ShareUtils.shareFile(getContext(), file);
            }
            mAlertDialog.cancel();
        });
    }

    /**
     * 根据项目名称模糊搜索
     *
     * @param searchContent 项目名称
     */
    public void searchProjects(String searchContent){
        List<Project> sortList = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Name.like("%" + searchContent + "%")).list();
        list.clear();
        list.addAll(sortList);
        adapter.notifyDataSetChanged();
    }
}
